import axios from 'axios'
import store from '@/store/index.ts'
import { errorAlert } from '@/store/alert'
import router from '@/router'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000,
})

service.interceptors.request.use(
  (config) => {
    //add token
    if (store.getters.token)
      config.headers['Authorization'] = store.getters.token

    if (store.getters.longlivedtoken)
      config.headers['LonglivedToken'] = store.getters.longlivedtoken

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    switch (res.code) {
      case 401:
        errorAlert(res.msg || '登录过期')
        store.dispatch('user/logout')
        router.push('/login')
        break
      case 403:
        errorAlert('没有权限')
        return Promise.reject(new Error(res.msg || 'Error'))
      case 404:
        errorAlert('请求的资源不存在')
        return Promise.reject(new Error(res.msg || 'Error'))
      case 500:
        console.log(res)
        errorAlert(res.msg || '服务器错误')
        return Promise.reject(new Error(res.msg || 'Error'))
      case 200:
        {
          const token = response.headers['Authorization']
          const longlivedToken = response.headers['LonglivedToken']
          if (token && longlivedToken) {
            store.commit('user/SET_TOKEN', token)
            store.commit('user/SET_LONG_LIVE_TOKEN', longlivedToken)
          }

          return res
        }
        break
    }
  },
  (error) => {
    errorAlert(error)
    console.error('err' + error)
    return Promise.reject(error)
  },
)

export default service
